import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@v/Layout'
import { isLogin, getRole } from '@/utils'
const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '仪表盘',
        meta: {
          roles: '*'
        },
        component: () => import('@v/DashBoard')
      },
      {
        path: '/itemLists',
        name: '商品管理',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@v/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@v/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '修改商品',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@v/ItemUpdate')
      },
      {
        path: '/cateLists',
        name: '商品分类管理',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@v/CateLists')
      },
      {
        path: '/userInfo',
        name: '个人中心',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@v/UserInfo')
      },
      {
        path: '/setting',
        name: '设置',
        meta: {
          roles: ['a', 'b']
        },
        component: () => import('@v/SettingPage')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: '*'
    },
    component: () => import('@v/LoginPage')
  },
  {
    path: '/noauth',
    name: 'noauth',
    meta: {
      roles: '*'
    },
    component: () => import('@v/NoPermission')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    meta: {
      roles: '*'
    },
    component: () => import('@v/NotFound')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由鉴权
router.beforeEach((to, from, next) => {
  const passRoutes = ['/login']
  if (passRoutes.includes(to.path)) {
    next()
  } else {
    // 非登录页 鉴权
    if (isLogin()) {
      // 判断 角色是否可以访问该路由
      if (to.meta.roles === '*' || to.meta.roles.includes(getRole())) {
        // 可以访问
        next()
      } else {
        next('/noauth')
      }
    } else {
      next('/login')
    }
  }
})
export default router
